package com.itheima.sys.util;

import com.itheima.common.util.JsonUtils;
import com.itheima.sys.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class HuanxinImManager {

    //注册用户接口地址
    private static final String registerUserRequestUrl = "http://a1.easemob.com/1113190916036866/nineclock/users";
    //获取访问令牌地址 路径占位符 参数一：Orgname企业名称 参数二：appname应用名称
    private static final String accessTokenRequestUrl = "http://a1.easemob.com/1113190916036866/nineclock/token";
    private static final String KEY_PREFIX = "nc:sys:hxtoken:nineclock";


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * (开发模式)注册用户到环信
     *
     * @param sysUsers
     */
    public void registerUserToHuanXinOpen(List<SysUser> sysUsers) {
        try {
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(registerUserRequestUrl, sysUsers, String.class);
            if (!responseEntity.getStatusCode().is2xxSuccessful()) {
                log.error("【系统微服务】注册{}到环信失败！失败原因：{}", sysUsers, responseEntity.getBody());
                return;
            }
            System.out.println(responseEntity);
        } catch (RestClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * （授权模式）注册用户到环信
     *
     * @param sysUsers
     */
    public void registerUserToHuanXinAuth(List<SysUser> sysUsers) {
        try {
            //拿到header信息
            String token = this.getToken();
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_JSON);
            requestHeaders.add("Authorization", "Bearer " + token);
            HttpEntity<String> requestEntity = new HttpEntity<String>(JsonUtils.toString(sysUsers), requestHeaders);
            String result = restTemplate.postForObject(registerUserRequestUrl, requestEntity, String.class);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取访问环信接口的token,将生成的令牌存入redis 有效期为60天 获取授权码 code
     * @return
     */
    private String getToken() {
        String token = redisTemplate.opsForValue().get(KEY_PREFIX);
        if (StringUtils.isNotBlank(token)) {
            return token;
        }

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("grant_type", "client_credentials");
        map.put("client_id", "YXA6jcyypVSlQWqm-WCfyfIlIA");
        map.put("client_secret", "YXA6zLHBMTwtHKVW2n_Nap6nAF5Ck8o");

        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(map, headers);
        //发送请求获取秘钥
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(accessTokenRequestUrl, request, String.class);

        Map<String, String> map1 = JsonUtils.toMap(stringResponseEntity.getBody(), String.class, String.class);
        System.out.println(map1);
        String access_token = map1.get("access_token");
        //将获取到授权码存入redis中
        redisTemplate.opsForValue().set(KEY_PREFIX, access_token, 59, TimeUnit.DAYS);
        return access_token;
    }
}
